package com.nbicc.common.utils;

import com.nbicc.myshiro.authc.AuthcUser;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by li on 17/12/25.
 */
public class AuthcUserUtil {

    /**
     * 用户信息存储在session中的字段
     */
    public static final String AUTHC_USER_KEY = "authcUser";

    /**
     * 往session中添加用户
     * @param authcUser
     */
    public static void setAuthcUser(AuthcUser authcUser) {
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        request.getSession().setAttribute(AUTHC_USER_KEY , authcUser);
    }

    /**
     * 获取当前会话登陆的用户
     * @return
     */
    public static AuthcUser getAuthcUser() {
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Object authcUser = request.getSession().getAttribute(AUTHC_USER_KEY);
        if(authcUser != null){
            return (AuthcUser) authcUser;
        }
        return null;
    }

    /**
     * 是否登陆
     * @return
     */
    public static boolean isLogin(){
        if(getAuthcUser() != null){
            return true;
        }
        return false;
    }

    /**
     * 登出(删除session中用户的登录信息)
     */
    public static void logout() {
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        request.getSession().removeAttribute(AUTHC_USER_KEY);
    }
}
